from fastapi import APIRouter, HTTPException

from .dto.run_id import RunId
from ..utils import envelope
from ..services.runs_service import list_runs_service, get_run_service, stop_run_service
from ..services.kafka_service import kafka_send_json, kafka_consumer_task, kafka_stop_consumer

router = APIRouter(prefix="/runs", tags=["runs"])


@router.post("/list")
def api_list_runs():
    return envelope(list_runs_service())


@router.post("/get")
def api_get_run(payload: RunId):
    r = get_run_service(payload.run_id)
    if not r:
        raise HTTPException(status_code=404, detail="Run not found")
    return envelope({"item": r})


@router.post("/stop")
def api_stop_run(payload: RunId):
    try:
        result = stop_run_service(payload.run_id)
        return envelope(result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to stop: {e}")